<template>
  <el-dialog
    v-model="dialogVisible"
    title="音频管理"
    width="600px"
    @close="handleClose"
  >
    <div class="audio-manager">
      <!-- 当前音频 -->
      <div class="current-audio" v-if="work">
        <h4>当前音频</h4>
        <div v-if="work.audioUrl" class="audio-info">
          <audio :src="work.audioUrl" controls style="width: 100%">
            您的浏览器不支持音频播放
          </audio>
          <div class="audio-actions">
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDeleteAudio"
              :loading="deleting"
            >
              删除音频
            </el-button>
          </div>
        </div>
        <div v-else class="no-audio">
          <el-empty description="暂无音频文件" :image-size="80" />
        </div>
      </div>

      <!-- 上传新音频 -->
      <div class="upload-section">
        <h4>上传新音频</h4>
        <el-upload
          ref="uploadRef"
          :action="uploadAction"
          :headers="uploadHeaders"
          :data="uploadData"
          :before-upload="beforeUpload"
          :on-change="handleFileChange"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :on-progress="handleUploadProgress"
          :auto-upload="false"
          accept="audio/*"
          drag
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将音频文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持 mp3, wav, aac, m4a 等音频格式，文件大小不超过 50MB
            </div>
          </template>
        </el-upload>

        <!-- 上传进度 -->
        <div v-if="uploading" class="upload-progress">
          <el-progress :percentage="uploadProgress" />
          <p>正在上传音频文件...</p>
        </div>

        

         <!-- 上传按钮 -->
         <div class="upload-actions" v-if="fileList.length > 0 && !uploading">
           <el-button @click="clearFiles">清空</el-button>
           <el-button type="primary" @click="submitUpload" :loading="uploading">
             开始上传
           </el-button>
         </div>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox, type UploadInstance, type UploadProps, type UploadRawFile } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { uploadWorkAudio, deleteWorkAudio } from '@/api/work'
import { useUserStore } from '@/stores/user'
import type { Work } from '@/types'

interface Props {
  modelValue: boolean
  work?: Work | null
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// Store
const userStore = useUserStore()

// 响应式数据
const uploadRef = ref<UploadInstance>()
const fileList = ref<any[]>([])
const uploading = ref(false)
const uploadProgress = ref(0)
const deleting = ref(false)

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 上传配置
const uploadAction = computed(() => {
  return props.work ? `/api/admin/works/${props.work.id}/audio` : ''
})

const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${userStore.token}`
}))

const uploadData = ref({})

// 文件变化处理
const handleFileChange = (file: any, elFileList: any[]) => {
  console.log('文件变化:', file, elFileList)
  // 更新我们的响应式 fileList
  if (elFileList.length > 0) {
    fileList.value = [elFileList[elFileList.length - 1]]
  }
}

// 上传前检查
const beforeUpload: UploadProps['beforeUpload'] = (rawFile: UploadRawFile) => {
  // 检查文件类型
  const isAudio = rawFile.type.startsWith('audio/')
  if (!isAudio) {
    ElMessage.error('只能上传音频文件!')
    return false
  }

  // 检查文件大小 (50MB)
  const isLt50M = rawFile.size / 1024 / 1024 < 50
  if (!isLt50M) {
    ElMessage.error('音频文件大小不能超过 50MB!')
    return false
  }

  // 将文件添加到我们的响应式 fileList
  fileList.value = [rawFile]
  console.log('beforeUpload - fileList length:', fileList.value.length)
  console.log('beforeUpload - uploading state:', uploading.value)

  return true
}

// 手动上传
const submitUpload = async () => {
  if (!props.work || fileList.value.length === 0) return

  try {
    uploading.value = true
    uploadProgress.value = 0
    
    const file = fileList.value[0].raw
    await uploadWorkAudio(props.work.id, file)
    
    ElMessage.success('音频上传成功')
    clearFiles()
    emit('success')
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('音频上传失败')
  } finally {
    uploading.value = false
    uploadProgress.value = 0
  }
}

// 上传成功
const handleUploadSuccess = (response: any, file: any) => {
  ElMessage.success('音频上传成功')
  clearFiles()
  emit('success')
}

// 上传失败
const handleUploadError = (error: any) => {
  console.error('上传失败:', error)
  ElMessage.error('音频上传失败')
  uploading.value = false
}

// 上传进度
const handleUploadProgress = (event: any) => {
  uploadProgress.value = Math.round(event.percent)
}

// 清空文件列表
const clearFiles = () => {
  fileList.value = []
  uploadRef.value?.clearFiles()
}

// 删除音频
const handleDeleteAudio = async () => {
  if (!props.work?.audioUrl) return

  try {
    await ElMessageBox.confirm(
      '确定要删除当前音频文件吗？此操作不可恢复。',
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    deleting.value = true
    await deleteWorkAudio(props.work.id)
    ElMessage.success('音频删除成功')
    emit('success')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('音频删除失败')
    }
  } finally {
    deleting.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  clearFiles()
  dialogVisible.value = false
}

// 监听work变化，重置状态
watch(() => props.work, () => {
  clearFiles()
  uploading.value = false
  uploadProgress.value = 0
})
</script>

<style lang="scss" scoped>
.audio-manager {
  .current-audio {
    margin-bottom: 30px;
    
    h4 {
      margin: 0 0 16px 0;
      color: #303133;
      font-size: 16px;
      font-weight: 600;
      display: flex;
      align-items: center;
      gap: 8px;
      
      &::before {
        content: '';
        width: 4px;
        height: 16px;
        background: linear-gradient(135deg, #409eff, #67c23a);
        border-radius: 2px;
      }
    }

    .audio-info {
      background: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 8px;
      padding: 16px;
      
      .audio-actions {
        margin-top: 12px;
        text-align: right;
      }
    }

    .no-audio {
      padding: 20px 0;
      text-align: center;
    }
  }

  .upload-section {
    h4 {
      margin: 0 0 16px 0;
      color: #303133;
      font-size: 16px;
      font-weight: 600;
      display: flex;
      align-items: center;
      gap: 8px;
      
      &::before {
        content: '';
        width: 4px;
        height: 16px;
        background: linear-gradient(135deg, #e6a23c, #f56c6c);
        border-radius: 2px;
      }
    }

    .upload-progress {
      margin: 20px 0;
      background: #f8f9fa;
      border-radius: 8px;
      padding: 16px;
      
      p {
        margin: 8px 0 0 0;
        color: #666;
        font-size: 14px;
        text-align: center;
      }
    }

    .upload-actions {
      margin-top: 16px;
      text-align: right;
      
      .el-button {
        margin-left: 8px;
        border-radius: 6px;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-1px);
        }
      }
    }
  }
}

:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
</style>
